package com.cxyd.modules.job.task.tcpTask;

import com.cxyd.modules.job.utils.TcpClient;
import com.cxyd.modules.wcs.dto.PostTcpDTO;
import com.cxyd.modules.wcs.dto.TcpIpDTO;
import com.cxyd.modules.wcs.service.PostTcpService;
import com.cxyd.modules.wcs.service.TcpIpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component("post-tcp")
@Slf4j
public class PostTcpTask {
    @Resource
    private PostTcpService postTcpService;
    @Resource
    private TcpIpService tcpIpService;

    //创建锁，防止并发情况出现
    private Lock lock = new ReentrantLock();

    public void scanPost() {
        lock.lock();
        //            优先获取一下代POST的信息
        PostTcpDTO postTcp = postTcpService.getPostTcp();
        if (postTcp == null) {
            lock.unlock();//释放锁
            return;
        }
        log.info("获取到待下发的指令：{}", postTcp);
//            判断所指向的设备是否在[wcs_tcp_ip]中配置
        TcpIpDTO tcpIp = tcpIpService.getTcpIpByDvcNo(postTcp.getDvcNo());
        if (tcpIp == null || StringUtils.isBlank(tcpIp.getHostIp())) {
            log.error("设备[{}]未配置TCP服务器地址", postTcp.getDvcNo());
            return;
        }
        try {
//            将获取到的信息发送至TCP服务器
            String response = TcpClient.sendAndReceive(tcpIp.getHostIp(), tcpIp.getPort(), postTcp.getPostMsg());
            log.info("[wcs_post_tcp]指令交互成功，response:{}", response);
//            收到反馈则处理反馈信息
            postTcpService.postTcpHandle(postTcp, response);
        } catch (Exception e) {
            postTcpService.postTcpHandle(postTcp, "error");
            log.error("指令下发失败", e.getMessage());
        } finally {
            lock.unlock();//释放锁
        }
    }
}
